/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>

*/
package cmd

import (
	"fmt"
	"os"

	"gitee.com/smewl13/registry-sync/v2/config"
	"gitee.com/smewl13/registry-sync/v2/logger"
	"gitee.com/smewl13/registry-sync/v2/mirror"
	"gitee.com/smewl13/toolkit"
	"github.com/spf13/cobra"
)

// rootCmd represents the base command when called without any subcommands
var (
	cfgFile string
	rootCmd = &cobra.Command{
		Use:   "registry-sync",
		Short: "用于同步自建docker registry",
		Long:  `用于同步自建docker registry, 可同步到多备用registry上`,
		// Uncomment the following line if your bare application
		// has an action associated with it:
		// Run: func(cmd *cobra.Command, args []string) { },
		Run: func(cmd *cobra.Command, args []string) {
			logger.Info("server starting ... ")
			mirror.Run()
		},
	}
)

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	err := rootCmd.Execute()
	if err != nil {
		os.Exit(1)
	}
}

func init() {
	// Here you will define your flags and configuration settings.
	// Cobra supports persistent flags, which, if defined here,
	// will be global for your application.

	// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.v2.yaml)")

	// Cobra also supports local flags, which will only run
	// when this action is called directly.
	// rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
	cobra.OnInitialize(initConfig)
	rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "conf/registry.toml", "config file")
}

func initConfig() {
	if !toolkit.IsFile(cfgFile) {
		err := fmt.Sprintf("配置文件不存在, %s", cfgFile)
		panic(err)
	}

	config.LoadConfig(cfgFile)
	logger.NewLog(config.Log)
}
